<template>
  <n-card
    title="价格历史"
    :bordered="false"
    class="item-chart-card"
    size="small"
  >
    <template #header-extra>
      <n-space align="center">
        <n-radio-group
          v-model:value="selectedPeriod"
          size="small"
          @update:value="changePeriod"
        >
          <n-radio-button
            v-for="period in chartPeriods"
            :key="period.value"
            :value="period.value"
          >
            {{ period.label }}
          </n-radio-button>
        </n-radio-group>

        <!-- 时间过滤按钮 -->
        <n-popover
          trigger="click"
          placement="bottom-end"
          :show="showTimeFilterPanel"
          @update:show="showTimeFilterPanel = $event"
          style="max-width: 400px;"
        >
          <template #trigger>
            <n-button
              size="small"
              type="tertiary"
              :secondary="selectedTimeFilter.length > 0"
            >
              <template #icon>
                <n-icon><svg viewBox="0 0 24 24"><path fill="currentColor" d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10s10-4.5 10-10S17.5 2 12 2M7.7 15.5L7 14.2l3-1.7V7h1.5v5.8l-3.8 2.7Z"/></svg></n-icon>
              </template>
              时间过滤
              <span v-if="selectedTimeFilter.length > 0" style="margin-left: 4px;">
                ({{ selectedTimeFilter.length }})
              </span>
            </n-button>
          </template>

          <!-- 时间过滤面板内容 -->
          <div class="time-filter-panel">
            <div class="time-filter-header">
              <span class="panel-title">选择显示时间点</span>
              <n-space size="small">
                <n-button size="tiny" @click="selectAllHours">全选</n-button>
                <n-button size="tiny" @click="clearAllHours">清空</n-button>
                <n-button size="tiny" @click="invertSelection">反选</n-button>
              </n-space>
            </div>

            <!-- 预设选项 -->
            <div class="time-filter-presets">
              <span class="preset-label">快速选择：</span>
              <n-space size="small" wrap>
                <n-tag
                  v-for="preset in timeFilterPresets"
                  :key="preset.label"
                  :type="arraysEqual(selectedTimeFilter, preset.value) ? 'primary' : 'default'"
                  checkable
                  :checked="arraysEqual(selectedTimeFilter, preset.value)"
                  @click="applyPreset(preset.value)"
                  size="small"
                >
                  {{ preset.label }}
                </n-tag>
              </n-space>
            </div>

            <!-- 小时选择网格 -->
            <div class="time-filter-hours">
              <div class="hours-grid">
                <n-checkbox
                  v-for="hour in hourOptions"
                  :key="hour.value"
                  :checked="selectedTimeFilter.includes(hour.value)"
                  @update:checked="toggleHour(hour.value, $event)"
                  size="small"
                >
                  {{ hour.label }}
                </n-checkbox>
              </div>
            </div>

            <!-- 底部操作 -->
            <div class="time-filter-footer">
              <n-space justify="space-between" align="center">
                <span class="selected-count">
                  已选择 {{ selectedTimeFilter.length }} 个时间点
                </span>
                <n-space size="small">
                  <n-button size="small" @click="resetTimeFilter">重置</n-button>
                  <n-button size="small" type="primary" @click="applyTimeFilter">应用</n-button>
                </n-space>
              </n-space>
            </div>
          </div>
        </n-popover>
      </n-space>
    </template>
    
    <div class="item-chart-container" :class="{ 'enlarged': enlarge, 'mobile': mobile }">
      <!-- 加载遮罩层 -->
      <div v-if="chartLoading" class="chart-loading-overlay">
        <loading-skeleton type="default" />
      </div>

      <div @click="handleChartClick" class="chart-click-area" :class="{ 'loading': chartLoading }">
        <VueApexCharts
          ref="chartRef"
          type="line"
          :height="getChartHeight()"
          :options="apexOptions"
          :series="apexSeries"
          @zoom="handleZoom"
          @reset-zoom="handleResetZoom"
        />
      </div>
    </div>

    <!-- 统计卡片 -->
    <n-divider />

    <n-grid :cols="4" :x-gap="12" class="stat-cards">
      <n-grid-item>
        <div class="stat-card stat-min">
          <div class="stat-label">最低哈夫币</div>
          <div class="stat-value">
            <TransitionNumber
              :value="displayMinPriceValue"
              :decimals="displayMinPriceValue % 1 === 0 ? 0 : 2"
              :suffix="priceUnit"
              text-color="#18A058"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
      <n-grid-item>
        <div class="stat-card stat-max">
          <div class="stat-label">最高哈夫币</div>
          <div class="stat-value">
            <TransitionNumber
              :value="displayMaxPriceValue"
              :decimals="displayMaxPriceValue % 1 === 0 ? 0 : 2"
              :suffix="priceUnit"
              text-color="#D03050"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
      <n-grid-item>
        <div class="stat-card stat-avg">
          <div class="stat-label">平均哈夫币</div>
          <div class="stat-value">
            <TransitionNumber
              :value="displayAvgPriceValue"
              :decimals="displayAvgPriceValue % 1 === 0 ? 0 : 2"
              :suffix="priceUnit"
              text-color="#F0A020"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
      <n-grid-item>
        <div class="stat-card stat-change">
          <div class="stat-label">变化值</div>
          <div class="stat-value" :class="{ 'price-up': displayChangeValue > 0, 'price-down': displayChangeValue < 0 }">
            <TransitionNumber
              :value="displayChangeValueValue"
              :decimals="displayChangeValueValue % 1 === 0 ? 0 : 2"
              :prefix="displayChangeValue > 0 ? '+' : ''"
              :suffix="priceUnit"
              :text-color="displayChangeValue > 0 ? '#18A058' : displayChangeValue < 0 ? '#D03050' : '#2080F0'"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
    </n-grid>

    <n-grid :cols="3" :x-gap="12" class="stat-cards secondary-stats">
      <n-grid-item>
        <div class="stat-card stat-start">
          <div class="stat-label">起始哈夫币</div>
          <div class="stat-value">
            <TransitionNumber
              :value="displayStartPriceValue"
              :decimals="displayStartPriceValue % 1 === 0 ? 0 : 2"
              :suffix="priceUnit"
              text-color="#909399"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
      <n-grid-item>
        <div class="stat-card stat-end">
          <div class="stat-label">结束哈夫币</div>
          <div class="stat-value">
            <TransitionNumber
              :value="displayEndPriceValue"
              :decimals="displayEndPriceValue % 1 === 0 ? 0 : 2"
              :suffix="priceUnit"
              text-color="#606266"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
      <n-grid-item>
        <div class="stat-card stat-percent">
          <div class="stat-label">变化率</div>
          <div class="stat-value" :class="{ 'price-up': changePercent > 0, 'price-down': changePercent < 0 }">
            <TransitionNumber
              :value="changePercent"
              :decimals="2"
              :prefix="changePercent > 0 ? '+' : ''"
              suffix="%"
              :text-color="changePercent > 0 ? '#18A058' : changePercent < 0 ? '#D03050' : '#8A2BE2'"
              :duration="600"
            />
          </div>
        </div>
      </n-grid-item>
    </n-grid>
  </n-card>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useMessage } from 'naive-ui'
import { getPriceHistory } from '@/api/items'
import VueApexCharts from 'vue3-apexcharts'
import type { ApexOptions } from 'apexcharts'
import { UserPreferences } from '@/utils/storage'
import { useThemeStore } from '@/stores/theme'
import TransitionNumber from './TransitionNumber.vue'
import LoadingSkeleton from '@/components/common/LoadingSkeleton.vue'

// 组件属性定义
interface Props {
  objectId: number
  currentPrice: number
  price24hAgo: number
  grade: number
  loading?: boolean
  enlarge?: boolean
  mobile?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  loading: false,
  enlarge: false,
  mobile: false
})

// 定义事件
const emit = defineEmits<{
  chartClick: []
}>()

const message = useMessage()
const themeStore = useThemeStore()

// 智能价格格式化函数
const formatPrice = (price: number, options: {
  forceUnit?: boolean,
  maxDecimals?: number,
  minDecimals?: number
} = {}) => {
  const { forceUnit = false, maxDecimals = 2, minDecimals = 0 } = options

  if (price === 0) return '0'

  const absPrice = Math.abs(price)

  // 小于1000的价格直接显示，不转换单位
  if (absPrice < 1000 && !forceUnit) {
    // 智能小数位数：如果是整数就不显示小数
    const isInteger = price % 1 === 0
    if (isInteger && minDecimals === 0) {
      return price.toString()
    }
    return price.toFixed(Math.max(minDecimals, isInteger ? 0 : Math.min(maxDecimals, 2)))
  }

  // 1000-9999的价格，根据情况决定是否转换
  if (absPrice < 10000 && !forceUnit) {
    const isInteger = price % 1 === 0
    if (isInteger && minDecimals === 0) {
      return price.toString()
    }
    return price.toFixed(Math.max(minDecimals, isInteger ? 0 : Math.min(maxDecimals, 2)))
  }

  // 10000以上转换为万单位
  const wanPrice = price / 10000
  const isInteger = wanPrice % 1 === 0

  if (isInteger && minDecimals === 0) {
    return `${wanPrice}W`
  }

  return `${wanPrice.toFixed(Math.max(minDecimals, isInteger ? 0 : Math.min(maxDecimals, 2)))}W`
}

// Y轴智能格式化 - 根据价格范围决定是否使用万单位
const formatYAxisPrice = (price: number) => {
  return formatPrice(price, { forceUnit: false, maxDecimals: 2 })
}

// 动态tooltip配置
const createTooltipConfig = () => {
  return {
    enabled: true,
    shared: false,
    intersect: false,
    theme: isDarkTheme.value ? 'dark' : 'light',
    x: {
      show: true,
      format: 'dd MMM yyyy HH:mm'
    },
    y: {
      formatter: (val: number) => formatYAxisPrice(val),
      title: {
        formatter: () => '哈夫币: '
      }
    }
  }
}
// 从用户偏好中读取上次选择的时间段，默认为7天
const selectedPeriod = ref(UserPreferences.getChartPeriod('7d'))
// 从用户偏好中读取时间点过滤设置，默认为空数组（显示所有时间点）
const selectedTimeFilter = ref<number[]>(UserPreferences.getChartTimeFilter([]))
// 时间过滤面板显示状态
const showTimeFilterPanel = ref(false)
const historyData = ref<any[]>([])
const rawHistoryData = ref<any[]>([])
const statisticsData = ref<any>({})
const labelTimeMap = ref<{ [label: string]: string }>({})

// 图表组件引用
const chartRef = ref<any>(null)

// 图表加载状态
const chartLoading = ref(false)
const chartRenderComplete = ref(false)
const loadingHideTimer = ref<number | null>(null)

// 性能优化相关
const isUpdating = ref(false)
const updateTimer = ref<number | null>(null)
const processedDataCache = ref<any[]>([])
const lastDataHash = ref('')

// 性能监控
const performanceMetrics = ref({
  lastUpdateTime: 0,
  dataProcessingTime: 0,
  chartRenderTime: 0,
  annotationUpdateTime: 0,
  networkRequestTime: 0,
  totalUpdateTime: 0,
  cacheHitCount: 0,
  cacheMissCount: 0
})

// 增强的性能监控函数
const trackPerformance = (operation: string, startTime: number) => {
  const endTime = performance.now()
  const duration = endTime - startTime

  switch (operation) {
    case 'dataProcessing':
      performanceMetrics.value.dataProcessingTime = duration
      break
    case 'chartRender':
      performanceMetrics.value.chartRenderTime = duration
      break
    case 'annotationUpdate':
      performanceMetrics.value.annotationUpdateTime = duration
      break
    case 'networkRequest':
      performanceMetrics.value.networkRequestTime = duration
      break
    case 'totalUpdate':
      performanceMetrics.value.totalUpdateTime = duration
      break
  }

  // 开发环境下的详细性能报告
  if (import.meta.env.DEV) {
    const thresholds = {
      dataProcessing: 50,
      chartRender: 100,
      annotationUpdate: 30,
      networkRequest: 2000,
      totalUpdate: 3000
    }

    const threshold = thresholds[operation as keyof typeof thresholds] || 100

    if (duration > threshold) {
      console.warn(`[性能警告] ${operation} 耗时过长: ${duration.toFixed(2)}ms (阈值: ${threshold}ms)`)
    }

    // 每次完整更新后输出性能报告
    if (operation === 'totalUpdate') {
      console.group('[性能报告] ItemPriceHistory 组件')
      console.log(`📊 数据处理: ${performanceMetrics.value.dataProcessingTime.toFixed(2)}ms`)
      console.log(`🎨 图表渲染: ${performanceMetrics.value.chartRenderTime.toFixed(2)}ms`)
      console.log(`📍 注释更新: ${performanceMetrics.value.annotationUpdateTime.toFixed(2)}ms`)
      console.log(`🌐 网络请求: ${performanceMetrics.value.networkRequestTime.toFixed(2)}ms`)
      console.log(`⏱️ 总耗时: ${duration.toFixed(2)}ms`)
      console.log(`💾 缓存命中: ${performanceMetrics.value.cacheHitCount} | 缓存未命中: ${performanceMetrics.value.cacheMissCount}`)
      console.groupEnd()
    }
  }
}



// 时间段选项
const chartPeriods = [
  { label: '24小时', value: '24h' },
  { label: '3天', value: '3d' },
  { label: '7天', value: '7d' },
  { label: '30天', value: '30d' },
  { label: '90天', value: '90d' },
  { label: '180天', value: '180d' }
]

// 时间点过滤预设选项
const timeFilterPresets = [
  { label: '全部时间', value: [] },
  { label: '工作时间', value: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18] },
  { label: '交易活跃', value: [10, 14, 16, 20, 22] },
  { label: '夜间时段', value: [0, 1, 2, 3, 4, 5, 6] },
  { label: '整点时间', value: [0, 6, 12, 18] }
]

// 生成24小时选项
const hourOptions = Array.from({ length: 24 }, (_, i) => ({
  label: `${i.toString().padStart(2, '0')}:00`,
  value: i
}))

// 颜色映射，根据等级动态设置，使用CSS变量
const gradeColors: Record<number, string> = {
  1: '#949595', // 灰
  2: '#188D14', // 绿
  3: '#658BCE', // 蓝
  4: '#9b61c8', // 紫
  5: '#e8a64e', // 橙
  6: '#cb464a'  // 红
}
const primaryColor = gradeColors[props.grade] || '#658BCE'

// 简化的主题配置 - 只用于tooltip.theme判断
const isDarkTheme = computed(() => themeStore.isDark)

// 响应式屏幕尺寸
const screenWidth = ref(window.innerWidth)
const screenHeight = ref(window.innerHeight)

// 监听屏幕尺寸变化
const updateScreenSize = () => {
  screenWidth.value = window.innerWidth
  screenHeight.value = window.innerHeight
  // 强制重新渲染图表以适应新尺寸
  setTimeout(() => {
    if (apexOptions.value.chart) {
      apexOptions.value.chart.height = parseInt(getChartHeight())
    }
  }, 100)
}

onMounted(() => {
  window.addEventListener('resize', updateScreenSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateScreenSize)

  // 清理定时器和缓存
  if (updateTimer.value) {
    clearTimeout(updateTimer.value)
    updateTimer.value = null
  }

  // 清理加载状态定时器
  if (loadingHideTimer.value) {
    clearTimeout(loadingHideTimer.value)
    loadingHideTimer.value = null
  }

  // 清理缓存数据
  processedDataCache.value = []
  extremePointsCache.value = null
  labelTimeMap.value = {}
  lastDataHash.value = ''

  if (import.meta.env.DEV) {
    console.log('[ItemPriceHistory] 组件已卸载，所有定时器和缓存已清理')
  }
})

// 计算图表高度 - 改为响应式computed
const chartHeight = computed(() => {
  if (props.mobile) {
    // 移动端模式
    return 300
  } else if (props.enlarge) {
    // PC端放大模式
    return 400
  } else {
    // PC端正常模式
    return 300
  }
})

const getChartHeight = () => chartHeight.value.toString()

// 统计卡片显示用 - 直接使用原始价格
const displayMinPrice = computed(() => statisticsData.value.min_price || 0)
const displayMaxPrice = computed(() => statisticsData.value.max_price || 0)
const displayAvgPrice = computed(() => statisticsData.value.avg_price || 0)
const displayStartPrice = computed(() => statisticsData.value.start_price || 0)
const displayEndPrice = computed(() => statisticsData.value.end_price || 0)
const displayChangeValue = computed(() => statisticsData.value.change_value || 0)

// 格式化后的价格单位
const priceUnit = computed(() => {
  const maxPrice = Math.max(
    Math.abs(statisticsData.value.min_price || 0),
    Math.abs(statisticsData.value.max_price || 0),
    Math.abs(statisticsData.value.avg_price || 0)
  )
  return maxPrice >= 10000 ? 'W' : ''
})

// 统计卡片显示的数值（处理万单位转换）
const displayMinPriceValue = computed(() => {
  const price = displayMinPrice.value
  return price >= 10000 ? price / 10000 : price
})
const displayMaxPriceValue = computed(() => {
  const price = displayMaxPrice.value
  return price >= 10000 ? price / 10000 : price
})
const displayAvgPriceValue = computed(() => {
  const price = displayAvgPrice.value
  return price >= 10000 ? price / 10000 : price
})
const displayStartPriceValue = computed(() => {
  const price = displayStartPrice.value
  return price >= 10000 ? price / 10000 : price
})
const displayEndPriceValue = computed(() => {
  const price = displayEndPrice.value
  return price >= 10000 ? price / 10000 : price
})
const displayChangeValueValue = computed(() => {
  const price = displayChangeValue.value
  return price >= 10000 ? price / 10000 : price
})

// 图表用 - 均价线（保持原始价格）
const avgPrice = computed(() => statisticsData.value.avg_price || 0)

const changePercent = computed(() => statisticsData.value.change_percent || 0)

// 数据验证函数
const validateStatisticsData = () => {
  if (!statisticsData.value || Object.keys(statisticsData.value).length === 0) {
    return { valid: true, warnings: [] }
  }

  const warnings: string[] = []
  const data = statisticsData.value

  // 检查价格数据的合理性
  if (data.avg_price && (data.avg_price < 0 || data.avg_price > 100000000)) {
    warnings.push(`平均价格异常: ${data.avg_price}`)
  }

  if (data.min_price && data.max_price && data.min_price > data.max_price) {
    warnings.push(`最低价格(${data.min_price})大于最高价格(${data.max_price})`)
  }

  if (data.avg_price && data.min_price && data.max_price) {
    if (data.avg_price < data.min_price || data.avg_price > data.max_price) {
      warnings.push(`平均价格(${data.avg_price})超出最低价格(${data.min_price})和最高价格(${data.max_price})范围`)
    }
  }

  // 检查变化百分比的合理性
  if (Math.abs(data.change_percent || 0) > 1000) {
    warnings.push(`价格变化百分比异常: ${data.change_percent}%`)
  }

  if (import.meta.env.DEV && warnings.length > 0) {
    console.group('[数据验证] 发现统计数据异常')
    warnings.forEach(warning => console.warn(warning))
    console.log('原始统计数据:', data)
    console.groupEnd()
  }

  return { valid: warnings.length === 0, warnings }
}

// 防抖函数
function debounce<T extends (...args: any[]) => any>(func: T, wait: number): T {
  let timeout: ReturnType<typeof setTimeout> | null = null
  return ((...args: any[]) => {
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => func(...args), wait)
  }) as T
}

// 现代化的降采样函数，使用函数式编程
// 注意：当前已移除降采样限制以显示所有数据点，此函数保留以备将来使用
function downsample<T>(data: T[], maxPoints = 200): T[] {
  if (data.length <= maxPoints) return data

  const step = data.length / maxPoints

  // 使用Array.from和map创建采样索引，然后映射到数据
  const sampledData = Array.from({ length: maxPoints }, (_, i) => {
    const index = Math.floor(i * step)
    return index < data.length ? data[index] : data[data.length - 1]
  })

  // 确保包含最后一个点
  if (sampledData[sampledData.length - 1] !== data[data.length - 1]) {
    sampledData[sampledData.length - 1] = data[data.length - 1]
  }

  return sampledData
}

// 生成数据哈希用于缓存比较
function generateDataHash(data: any[]): string {
  if (!data.length) return ''
  return `${data.length}-${data[0]?.time || ''}-${data[data.length - 1]?.time || ''}`
}

// ApexCharts数据与配置
const apexSeries = ref<{ name: string; data: { x: string; y: number }[] }[]>([
  {
    name: '哈夫币价格',
    data: []
  }
])
const apexOptions = ref<ApexOptions>({
  chart: {
    type: 'line',
    height: parseInt(getChartHeight()),
    toolbar: { show: true },
    zoom: { enabled: true },
    animations: {
      enabled: true,
      speed: 800,
      animateGradually: {
        enabled: true,
        delay: 150
      },
      dynamicAnimation: {
        enabled: true,
        speed: 350
      }
    }
  },
  xaxis: {
    type: 'category',
    labels: {
      style: { colors: '#666666', fontSize: '11px' },
      rotate: -75
    },
    tickAmount: 20,
  },
  yaxis: {
    labels: {
      formatter: (val: number) => formatYAxisPrice(val),
      style: { colors: '#666666', fontSize: '11px' }
    },
    title: { text: '价格', style: { color: '#888888', fontSize: '12px' } }
  },
  stroke: { curve: 'smooth', width: 3, colors: [primaryColor] },
  colors: [primaryColor],
  markers: {
    size: 3,
    colors: [primaryColor],
    strokeColors: [primaryColor],
    strokeWidth: 2
  },
  fill: {
    type: 'solid',
    opacity: 1
  },
  annotations: {
    yaxis: [
      {
        y: avgPrice.value,
        borderColor: '#F0A020',
        strokeDashArray: 6,
        label: {
          borderColor: '#F0A020',
          style: {
            color: '#fff',
            background: '#F0A020',
            fontSize: '12px',
            fontWeight: 700
          },
          text: `均价: ${formatYAxisPrice(avgPrice.value)}`
        }
      }
    ],
    points: [] // 添加空的points数组，供后续更新使用
  },
  tooltip: createTooltipConfig(),
  grid: { borderColor: 'rgba(0, 0, 0, 0.05)', strokeDashArray: 4 },
  legend: {
    show: true,
    position: 'top',
    labels: { colors: '#888888', useSeriesColors: false }
  }
})

// 数据转换辅助函数
const transformDataItem = (item: any) => {
  if (typeof item.time === 'string') {
    const weekMap = ['日', '一', '二', '三', '四', '五', '六']
    const date = new Date(item.time.replace(' ', 'T'))
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const week = weekMap[date.getDay()]
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    const label = `${month}月${day}日 ${week} ${hour}:${minute}`

    // 建立label到time的映射
    labelTimeMap.value[label] = item.time

    return {
      x: label,
      y: Number(item.price),
      rawTime: item.time
    }
  } else {
    return {
      x: '',
      y: Number(item.price),
      rawTime: item.time
    }
  }
}

// 时间点过滤辅助函数
const arraysEqual = (arr1: number[], arr2: number[]): boolean => {
  if (arr1.length !== arr2.length) return false
  const sorted1 = [...arr1].sort((a, b) => a - b)
  const sorted2 = [...arr2].sort((a, b) => a - b)
  return sorted1.every((val, index) => val === sorted2[index])
}

// 根据选中的时间点过滤数据
const filterDataByTimePoints = (dataSource: any[]): any[] => {
  if (!dataSource.length || selectedTimeFilter.value.length === 0) {
    return dataSource // 如果没有选择时间点，返回所有数据
  }

  return dataSource.filter((item: any) => {
    if (typeof item.time === 'string') {
      const date = new Date(item.time.replace(' ', 'T'))
      const hour = date.getHours()
      return selectedTimeFilter.value.includes(hour)
    }
    return true // 如果时间格式不正确，保留数据
  })
}

// 现代化的数据处理函数 - 使用函数式编程
const processChartData = (dataSource: any[]): any[] => {
  if (!dataSource.length) return []

  // 先进行时间点过滤，再进行数据转换
  const filteredData = filterDataByTimePoints(dataSource)

  // 使用map进行数据转换，更简洁优雅
  return filteredData.map(transformDataItem)
}

// 优化的图表更新函数 - 分离数据更新和配置更新
const updateApexChart = (customData?: any[]) => {
  if (isUpdating.value) return

  const chartStartTime = performance.now()
  const dataSource = customData || rawHistoryData.value

  if (!dataSource.length) {
    apexSeries.value[0].data = []
    return
  }

  // 检查数据是否变化，使用缓存
  const dataHash = generateDataHash(dataSource)
  if (!customData && dataHash === lastDataHash.value && processedDataCache.value.length > 0) {
    apexSeries.value[0].data = processedDataCache.value
    performanceMetrics.value.cacheHitCount++
    return
  }

  performanceMetrics.value.cacheMissCount++
  isUpdating.value = true

  try {
    let processedData = processChartData(dataSource)

    // 渲染所有数据点，不进行降采样（根据用户要求显示所有数据）
    if (!customData) {
      // processedData = downsample(processedData, 200) // 已移除降采样限制
      processedDataCache.value = processedData
      lastDataHash.value = dataHash
    }

    // 使用 nextTick 确保数据更新的时机
    nextTick(() => {
      apexSeries.value[0].data = processedData

      // 分离配置更新 - 只在必要时更新
      if (apexOptions.value.xaxis) {
        const newTickAmount = Math.min(20, Math.floor(processedData.length / 5))
        if (apexOptions.value.xaxis.tickAmount !== newTickAmount) {
          apexOptions.value.xaxis.tickAmount = newTickAmount
        }
      }

      // 数据更新完成后，立即更新注释标记
      nextTick(() => {
        updateAnnotations()
      })

      // 性能监控
      trackPerformance('chartRender', chartStartTime)
    })
  } finally {
    isUpdating.value = false
  }
}
// 创建防抖的更新函数
const debouncedUpdateChart = debounce(updateApexChart, 100)
const debouncedRefreshChart = debounce(() => {
  if (apexOptions.value.chart) {
    apexOptions.value.chart.height = parseInt(getChartHeight())
  }
  updateApexChart()
}, 150)

// 监听historyData变化，使用防抖更新
watch(historyData, () => {
  debouncedUpdateChart()
}, { deep: false })

// 监听时间过滤变化，自动更新图表
watch(selectedTimeFilter, () => {
  // 清理缓存以确保过滤生效
  lastDataHash.value = ''
  processedDataCache.value = []
  debouncedUpdateChart()
}, { deep: true })

// 监听关键props变化，使用防抖刷新
watch([() => props.objectId, () => props.enlarge, () => props.mobile], () => {
  // 清理缓存当objectId变化时
  if (props.objectId) {
    lastDataHash.value = ''
    processedDataCache.value = []
    labelTimeMap.value = {}
  }
  debouncedRefreshChart()
}, { deep: false })

// 智能加载状态管理
const hideLoadingWithDelay = () => {
  // 清除之前的定时器
  if (loadingHideTimer.value) {
    clearTimeout(loadingHideTimer.value)
  }

  // 等待图表完全渲染后延迟500ms移除加载遮罩
  loadingHideTimer.value = setTimeout(() => {
    chartLoading.value = false
    chartRenderComplete.value = true

    if (import.meta.env.DEV) {
      console.log('[加载状态] 图表渲染完成，加载遮罩已移除')
    }
  }, 500) as any
}



// 切换图表时间段 - 优化加载状态管理
const changePeriod = async (period: string) => {
  // 防止重复点击
  if (chartLoading.value) return

  selectedPeriod.value = period
  // 保存用户选择到本地存储
  UserPreferences.setChartPeriod(period)

  // 显示加载状态
  chartLoading.value = true
  chartRenderComplete.value = false

  if (import.meta.env.DEV) {
    console.log(`[加载状态] 开始切换到时间段: ${period}`)
  }

  try {
    await updateChart()

    // 确保图表数据更新完成
    await nextTick()

    // 等待图表渲染完成后再隐藏加载状态
    hideLoadingWithDelay()

  } catch (error) {
    console.error('切换时间段失败:', error)
    chartLoading.value = false
    message.error('切换时间段失败，请重试')
  }
}



// 获取价格历史数据
const updateChart = async () => {
  if (!props.objectId) return

  const networkStartTime = performance.now()
  const totalStartTime = performance.now()

  try {
    const response = await getPriceHistory(props.objectId, selectedPeriod.value)

    // 网络请求性能监控
    trackPerformance('networkRequest', networkStartTime)

    if (response.code === 1 && response.data && (response.data as any).history) {
      const newHistory = (response.data as any).history
      const newStatistics = (response.data as any).statistics || {}

      // 检查数据是否真的变化了
      const newDataHash = generateDataHash(newHistory)
      if (newDataHash !== lastDataHash.value) {
        rawHistoryData.value = newHistory
        historyData.value = newHistory
        statisticsData.value = newStatistics

        // 数据验证
        const validation = validateStatisticsData()
        if (!validation.valid && import.meta.env.DEV) {
          console.warn('[数据验证] 统计数据存在异常，但继续处理')
        }

        // 清理缓存
        extremePointsCache.value = null

        // 使用防抖更新
        nextTick(() => {
          debouncedUpdateChart()
          // 总体性能监控
          trackPerformance('totalUpdate', totalStartTime)
        })
      }
    } else {
      rawHistoryData.value = []
      historyData.value = []
      statisticsData.value = {}
      lastDataHash.value = ''
      processedDataCache.value = []
      extremePointsCache.value = null
    }
  } catch (error) {
    rawHistoryData.value = []
    historyData.value = []
    statisticsData.value = {}
    lastDataHash.value = ''
    processedDataCache.value = []
    extremePointsCache.value = null
    message.error('获取价格历史数据失败')
  }
}

// 优化的图表刷新函数
const refreshChart = () => {
  if (isUpdating.value) return

  if (updateTimer.value) {
    clearTimeout(updateTimer.value)
  }

  updateTimer.value = setTimeout(() => {
    if (apexOptions.value.chart) {
      apexOptions.value.chart.height = parseInt(getChartHeight())
    }
    updateApexChart()
    updateTimer.value = null
  }, 50) as any
}

// 时间过滤交互函数
const selectAllHours = () => {
  selectedTimeFilter.value = Array.from({ length: 24 }, (_, i) => i)
}

const clearAllHours = () => {
  selectedTimeFilter.value = []
}

const invertSelection = () => {
  const allHours = Array.from({ length: 24 }, (_, i) => i)
  selectedTimeFilter.value = allHours.filter(hour => !selectedTimeFilter.value.includes(hour))
}

const toggleHour = (hour: number, checked: boolean) => {
  if (checked) {
    if (!selectedTimeFilter.value.includes(hour)) {
      selectedTimeFilter.value.push(hour)
    }
  } else {
    const index = selectedTimeFilter.value.indexOf(hour)
    if (index > -1) {
      selectedTimeFilter.value.splice(index, 1)
    }
  }
}

const applyPreset = (preset: number[]) => {
  selectedTimeFilter.value = [...preset]
}

const resetTimeFilter = () => {
  selectedTimeFilter.value = []
  UserPreferences.setChartTimeFilter([])
  updateApexChart()
}

const applyTimeFilter = () => {
  // 保存设置到持久化存储
  UserPreferences.setChartTimeFilter(selectedTimeFilter.value)
  // 关闭面板
  showTimeFilterPanel.value = false
  // 重新渲染图表
  updateApexChart()

  if (import.meta.env.DEV) {
    console.log('[时间过滤] 应用时间点过滤:', selectedTimeFilter.value)
  }
}

// 处理图表点击事件
const handleChartClick = () => {
  if (!props.enlarge) {
    emit('chartClick')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  if (props.objectId) {
    updateChart()
  }
  // 确保图表在挂载后正确渲染
  setTimeout(refreshChart, 100)

  // 开发环境下输出性能监控信息
  if (import.meta.env.DEV) {
    console.log('[ItemPriceHistory] 组件已挂载，性能监控已启用')
  }
})

// 缓存的最高最低点计算
const extremePointsCache = ref<{ max: any; min: any; dataLength: number } | null>(null)

// 现代化的最高价和最低价计算，使用函数式编程
const maxPoint = computed(() => {
  const arr = apexSeries.value[0].data
  if (!arr.length) return null

  // 检查缓存
  if (extremePointsCache.value && extremePointsCache.value.dataLength === arr.length) {
    return extremePointsCache.value.max
  }

  // 使用函数式方法计算最大最小值
  const maxPoint = arr.reduce((max, current, index) =>
    current.y > max.y ? { ...current, idx: index } : max,
    { ...arr[0], idx: 0 }
  )

  const minPoint = arr.reduce((min, current, index) =>
    current.y < min.y ? { ...current, idx: index } : min,
    { ...arr[0], idx: 0 }
  )

  // 更新缓存
  extremePointsCache.value = {
    max: maxPoint,
    min: minPoint,
    dataLength: arr.length
  }

  return maxPoint
})

const minPoint = computed(() => {
  const arr = apexSeries.value[0].data
  if (!arr.length) return null

  // 检查缓存
  if (extremePointsCache.value && extremePointsCache.value.dataLength === arr.length) {
    return extremePointsCache.value.min
  }

  // 如果缓存无效，触发maxPoint计算来更新缓存
  maxPoint.value // 触发计算
  return extremePointsCache.value?.min || null
})

// 优化的配置更新机制 - 避免重复创建完整配置对象
const updateChartConfig = debounce(() => {
  // 只更新需要变化的配置部分
  if (apexOptions.value.chart) {
    apexOptions.value.chart.height = parseInt(getChartHeight())
  }

  // 更新颜色相关配置
  if (apexOptions.value.stroke) {
    apexOptions.value.stroke.colors = [primaryColor]
  }
  if (apexOptions.value.colors) {
    apexOptions.value.colors = [primaryColor]
  }
  if (apexOptions.value.markers) {
    apexOptions.value.markers.colors = [primaryColor]
    apexOptions.value.markers.strokeColors = [primaryColor]
  }
}, 100)

// 分离不同类型的配置更新
watch([() => props.enlarge, () => props.mobile, chartHeight], () => {
  updateChartConfig()
}, { deep: false })

watch(() => primaryColor, (newColor) => {
  if (apexOptions.value.stroke) {
    apexOptions.value.stroke.colors = [newColor]
  }
  if (apexOptions.value.colors) {
    apexOptions.value.colors = [newColor]
  }
  if (apexOptions.value.markers) {
    apexOptions.value.markers.colors = [newColor]
    apexOptions.value.markers.strokeColors = [newColor]
  }
}, { deep: false })

// 监听主题变化，更新tooltip主题
watch(() => themeStore.isDark, () => {
  // 更新tooltip主题
  if (apexOptions.value.tooltip) {
    apexOptions.value.tooltip.theme = themeStore.isDark ? 'dark' : 'light'
  }
}, { deep: false })

// 使用方法 API 添加点注释
const addPointAnnotationsWithAPI = () => {
  if (!chartRef.value || !chartRef.value.chart) return

  const chart = chartRef.value.chart

  // 清除所有现有的点注释
  chart.clearAnnotations()

  // 重新添加均价线
  if (avgPrice.value) {
    chart.addYaxisAnnotation({
      y: avgPrice.value,
      borderColor: '#F0A020',
      strokeDashArray: 6,
      label: {
        borderColor: '#F0A020',
        style: {
          color: '#fff',
          background: '#F0A020',
          fontSize: '12px',
          fontWeight: 700
        },
        text: `均价: ${formatYAxisPrice(avgPrice.value)}`
      }
    })
  }

  // 添加最高点注释
  if (maxPoint.value) {
    chart.addPointAnnotation({
      x: maxPoint.value.x,
      y: maxPoint.value.y,
      marker: {
        size: 8,
        fillColor: '#D03050',
        strokeColor: '#fff',
        strokeWidth: 2,
        shape: 'circle'
      },
      label: {
        borderColor: '#D03050',
        style: { color: '#fff', background: '#D03050', fontSize: '12px', fontWeight: 700 },
        text: `最高: ${formatYAxisPrice(maxPoint.value.y)}`,
        offsetY: 0
      }
    })
  }

  // 添加最低点注释
  if (minPoint.value) {
    chart.addPointAnnotation({
      x: minPoint.value.x,
      y: minPoint.value.y,
      marker: {
        size: 8,
        fillColor: '#18A058',
        strokeColor: '#fff',
        strokeWidth: 2,
        shape: 'circle'
      },
      label: {
        borderColor: '#18A058',
        style: { color: '#fff', background: '#18A058', fontSize: '12px', fontWeight: 700 },
        text: `最低: ${formatYAxisPrice(minPoint.value.y)}`,
        offsetY: 40
      }
    })
  }
}

// 优化注释更新 - 使用防抖避免频繁更新
const updateAnnotations = debounce(() => {
  const startTime = performance.now()

  // 尝试使用方法 API
  addPointAnnotationsWithAPI()

  // 性能监控
  trackPerformance('annotationUpdate', startTime)
}, 150)

watch([avgPrice, maxPoint, minPoint], () => {
  updateAnnotations()
}, { deep: false })

// 绑定ApexCharts zoom/resetZoom事件
function handleZoom(_e: any, chartContext: any, config: any) {
  const minIdx = config.xaxis?.min
  const maxIdx = config.xaxis?.max
  if (minIdx == null || maxIdx == null) return
  const labels = chartContext?.w?.globals?.categoryLabels
  if (!labels || !labels.length) return
  const minLabel = labels[Math.floor(minIdx)]
  const maxLabel = labels[Math.ceil(maxIdx)]
  // 用label反查原始time
  const minTime = labelTimeMap.value[minLabel]
  const maxTime = labelTimeMap.value[maxLabel]
  if (!minTime || !maxTime) return
  // 用time区间筛选rawHistoryData
  const [startTime, endTime] = minTime <= maxTime ? [minTime, maxTime] : [maxTime, minTime]
  const zoomed = rawHistoryData.value.filter((item: any) => item.time >= startTime && item.time <= endTime)
  updateApexChart(zoomed)
  if (zoomed.length > 2000) message.warning('区间数据过多，可能会卡顿')
}
function handleResetZoom() {
  updateApexChart() // 恢复显示所有数据
}
</script>

<style scoped>
.item-chart-card {
  margin-bottom: 16px;
  /* 移动端触摸优化 */
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

.item-chart-card.landscape-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  border-radius: 0;
  z-index: 999;
  background: var(--item-card-bg);
}
.item-chart-container {
  height: 300px;
  width: 100%;
  min-height: 300px;
  position: relative;
  overflow: hidden;
  /* 确保SVG图表正确渲染 */
  display: block;
}

/* 图表加载遮罩层 */
.chart-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--item-card-bg);
  opacity: 0.9;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  backdrop-filter: blur(2px);
  border-radius: 8px;
}

.loading-text {
  color: var(--item-text-secondary);
  font-size: 14px;
  margin-top: 8px;
}

/* 加载状态下的图表区域 */
.chart-click-area.loading {
  opacity: 0.3;
  pointer-events: none;
  transition: opacity 0.3s ease;
}

/* 确保ApexCharts SVG正确显示 */
.item-chart-container :deep(.apexcharts-canvas) {
  width: 100% !important;
  height: 100% !important;
}

.item-chart-container :deep(.apexcharts-svg) {
  width: 100% !important;
  height: 100% !important;
}

/* 图表点击区域 */
.chart-click-area {
  width: 100%;
  height: 100%;
  cursor: pointer;
  position: relative;
}

.chart-click-area:hover {
  background: var(--item-hover-bg);
  border-radius: 4px;
}

/* 放大模式下不显示点击效果 */
.item-chart-container.enlarged .chart-click-area {
  cursor: default;
}

.item-chart-container.enlarged .chart-click-area:hover {
  background: transparent;
}

.item-chart-container.enlarged {
  height: 400px;
  min-height: 400px;
}

.item-chart-container.mobile {
  height: 300px;
  min-height: 300px;
  width: 100%;
}



/* 移动端优化 */
@media (max-width: 900px) {
  .item-chart-card {
    margin-bottom: 12px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  }

  .item-chart-container {
    height: 280px;
    min-height: 280px;
    margin: 8px 0;
  }

  .item-chart-container.mobile {
    height: 280px;
    min-height: 280px;
  }

  /* 移动端统计卡片优化 */
  .stat-cards {
    margin-top: 16px;
    gap: 8px !important;
  }

  .stat-card {
    min-height: 60px;
    padding: 8px 4px;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  }

  .stat-label {
    font-size: 12px;
    margin-bottom: 4px;
    color: #666;
  }

  .stat-value {
    font-size: 16px;
    font-weight: 600;
    line-height: 1.2;
  }

  /* 优化头部按钮区域 */
  .n-card-header {
    padding: 12px 16px !important;
  }

  .n-radio-group {
    transform: scale(0.9);
    transform-origin: right center;
  }

  .n-radio-button {
    font-size: 12px !important;
    padding: 4px 8px !important;
    min-height: 36px;
  }
}

/* 中等屏幕优化 */
@media (max-width: 600px) {
  .item-chart-container {
    height: 240px;
    min-height: 240px;
    margin: 4px 0;
  }

  .stat-cards {
    margin-top: 12px;
    gap: 6px !important;
  }

  .stat-card {
    min-height: 50px;
    padding: 6px 2px;
  }

  .stat-label {
    font-size: 11px;
  }

  .stat-value {
    font-size: 14px;
  }

  /* 优化头部 */
  .n-card-header {
    padding: 8px 12px !important;
  }

  .n-radio-group {
    transform: scale(0.85);
  }

  .n-radio-button {
    font-size: 11px !important;
    padding: 3px 6px !important;
    min-height: 32px;
  }
}

/* 小屏幕优化 */
@media (max-width: 375px) {
  .item-chart-container {
    height: 200px;
    min-height: 200px;
    margin: 2px 0;
  }

  .stat-cards {
    margin-top: 8px;
    gap: 4px !important;
  }

  .stat-card {
    min-height: 44px;
    padding: 4px 2px;
  }



  /* 优化头部 */
  .n-card-header {
    padding: 6px 8px !important;
  }

  .n-radio-group {
    transform: scale(0.8);
  }

  .n-radio-button {
    padding: 2px 4px !important;
    min-height: 28px;
  }
}
.item-price-chart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}
.stat-cards { margin-top: 16px; }
.secondary-stats { margin-top: 12px; }
.stat-card {
  background: var(--item-card-bg);
  border-radius: 6px;
  padding: 8px 0;
  text-align: center;
  box-shadow: var(--item-shadow-light);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.stat-card:hover {
  transform: translateY(-1px);
  box-shadow: var(--item-shadow-medium);
}
.stat-label { font-size: 12px; color: var(--item-text-secondary); margin-bottom: 2px; }
.stat-value { font-size: 18px; font-weight: bold; transition: color 0.3s ease; line-height: 1.2; }
.price-change-container {
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.price-change-label { color: var(--item-text-secondary); font-size: 14px; }
.price-change-value {
  font-size: 16px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
}
.price-up { color: #18A058 !important; }
.price-down { color: #D03050 !important; }
.stat-value.price-up { color: #18A058 !important; }
.stat-value.price-down { color: #D03050 !important; }

/* 时间过滤面板样式 */
.time-filter-panel {
  width: 380px;
  padding: 16px;
}

.time-filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--n-divider-color);
}

.panel-title {
  font-weight: 600;
  font-size: 14px;
  color: var(--n-text-color);
}

.time-filter-presets {
  margin-bottom: 16px;
}

.preset-label {
  font-size: 12px;
  color: var(--n-text-color-2);
  margin-bottom: 8px;
  display: block;
}

.time-filter-hours {
  margin-bottom: 16px;
}

.hours-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.hours-grid .n-checkbox {
  font-size: 12px;
  min-width: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.time-filter-footer {
  padding-top: 12px;
  border-top: 1px solid var(--n-divider-color);
}

.selected-count {
  font-size: 12px;
  color: var(--n-text-color-2);
}

/* 移动端时间过滤面板优化 */
@media (max-width: 600px) {
  .time-filter-panel {
    width: 320px;
    padding: 12px;
  }

  .hours-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 6px;
  }

  .time-filter-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

</style>

<style>
/* 强制ApexCharts x轴标签斜着展示 */
::v-deep .apexcharts-xaxis-label {
  transform: rotate(-45deg) !important;
  text-anchor: end !important;
}

/* ApexCharts tooltip 主题适配 - 使用内置主题并进行微调 */
:global(.apexcharts-tooltip.apexcharts-theme-dark) {
  background: rgba(50, 50, 50, 0.95) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
}

:global(.apexcharts-tooltip.apexcharts-theme-light) {
  background: rgba(255, 255, 255, 0.95) !important;
  border: 1px solid rgba(0, 0, 0, 0.1) !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}
</style>
